package org.gthelper.handler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.gthelper.data.DataGeter;
import org.gthelper.database.FileInfo;
import org.gthelper.database.FileStatus;
import org.gthelper.error.ErrorCode;
import org.gthelper.order.OrderInfo;


public class PreUpload extends Handler
{

	@Override
	public int handle(OrderInfo orderinfo) {
		// TODO 自动生成的方法存根
		//get id
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				DataGeter dg = new DataGeter();
				int errcode=dg.getData(orderinfo.orderStream, baos);
				if(errcode!=ErrorCode.NORMAL)return errcode;
				byte[] userid = baos.toByteArray();
				baos.reset();
				
				//get filename
				errcode = dg.getData(orderinfo.orderStream, baos);
				if(errcode!=ErrorCode.NORMAL)return errcode;
				byte[] filename = baos.toByteArray();
				baos.reset();
				
				//to String
				String usrid="";
				String fileName="";
				try {
					usrid = new String(userid,"UTF-8");
					fileName = new String(filename,"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
					return ErrorCode.UNKNOWN;
				}
				if((fileName.indexOf('/'))>-1)return ErrorCode.WRONGNAME;
				if((fileName.indexOf('\\'))>-1)return ErrorCode.WRONGNAME;
				//check
				FileInfo fileinfo=null;
				try {
					fileinfo = FileInfo.getfileInfobyuserIDandfilename(usrid, fileName);
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
					return ErrorCode.DATABASEERR;
				}
				if(fileinfo!=null)
				{if(fileinfo.getstatus()!=FileStatus.uploaderr)return ErrorCode.FILEEXIST;}
				
				if(fileinfo==null)
				{
					FileInfo.insertnewfileinfo(usrid, fileName, FileStatus.waitupload);
				}
				else
				{
					fileinfo.setstatus(FileStatus.waitupload);
					fileinfo.updatefilelist();
				}
				
				DataOutputStream dos = new DataOutputStream(orderinfo.mainOutput);
				try {
					dos.writeLong(1);
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				
				return ErrorCode.NORMAL;
				
	}
	
}